package cc.laop.service;

import cc.laop.constants.Constants;
import cc.laop.entity.ContentEntity;
import cc.laop.utils.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by Pengpeng on 2017/5/17.
 */
@Service
public class ContentService {

    @Autowired
    private RedisService redisService;

    public ContentEntity get(String key) {
        if (StringUtils.isNotEmpty(key)) {
            return (ContentEntity) redisService.hashGet(Constants.NOTE_REDIS_KEY, key);
        } else {
            return null;
        }
    }

    public ContentEntity add() {
        String key = RandomUtils.randomCode(8);
        ContentEntity content = new ContentEntity();
        content.setKey(key);
        content.setCreateTime(new Date());
        redisService.hashPut(Constants.NOTE_REDIS_KEY, key, content);
        return content;
    }

    public void update(ContentEntity content) {
        if (content != null) {
            if (content.getPassword() != null) {
                content.setProtected(true);
            }
            redisService.hashPut(Constants.NOTE_REDIS_KEY, content.getKey(), content);
        }
    }

}
